package com.lancoo.znbkxx.uis;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lancoo.znbkxx.R;
import com.lancoo.znbkxx.adapter.AllPaperAdapter;
import com.lancoo.znbkxx.base.AppApplication;
import com.lancoo.znbkxx.base.BaseActivity;
import com.lancoo.znbkxx.beans.SampleGroupBean;
import com.lancoo.znbkxx.beans.SamplePaperBean;
import com.githang.statusbar.StatusBarCompat;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Create by TangJun on 2019/2/16
 */
public class AllPaperActivity extends BaseActivity implements View.OnClickListener{
    public static final String INTENT_KEY_ROOM_ENTITY = "groupBean";
    public static final String INTENT_KEY_ROOM_NAME = "groupName";
    private TextView tvTitleName;
    private ImageView ivExpand;
    private RecyclerView rvAll;
    private ImageView ivBack;
    private View mPopView;
    private PopupWindow mPopupWindow;
    private List<SamplePaperBean> mSearchList;
    private SampleGroupBean sampleGroupBean;
    private EditText mEditText;
    private String titleName;
    private AllPaperAdapter allPaperAdapter;
    private List<SamplePaperBean> samplePaperBeans;
    private long mLastSearchTime;
    private ImageView noDate;
    public static Intent getInstance(List<SamplePaperBean> samplePaperBeanList, String name) {
        Intent intent = new Intent(AppApplication.getInstance(), AllPaperActivity.class);
        intent.putExtra(INTENT_KEY_ROOM_ENTITY, (Serializable) samplePaperBeanList);
        intent.putExtra(INTENT_KEY_ROOM_NAME,name);
        return intent;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_allpaper);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.color_2884EC));
        samplePaperBeans = (List<SamplePaperBean>)getIntent().getSerializableExtra(INTENT_KEY_ROOM_ENTITY);
        titleName = getIntent().getStringExtra(INTENT_KEY_ROOM_NAME);
        /*samplePaperBeans = new ArrayList<>();
        for (int i = 0; i < sampleGroupBean.getChildCount()-1; i++) {
            samplePaperBeans.add(sampleGroupBean.getChildAt(i));
            //Log.i("tj",sampleGroupBean.getChildAt(i).toString()+"101");
        }*/
        initPopWindow();
        findViews();
    }

    private void findViews() {
        tvTitleName = findViewById(R.id.tv_title);
        ivExpand = findViewById(R.id.iv_expand);
        rvAll = findViewById(R.id.rv_allpaper);
        ivBack = findViewById(R.id.iv_back);
        mEditText = findViewById(R.id.etSearch);
        noDate = findViewById(R.id.iv_nodate);
        ivBack.setOnClickListener(this);
        ivExpand.setOnClickListener(this);
        tvTitleName.setText(titleName);
        ivExpand.setOnClickListener(this);
        ivExpand.setImageResource(mPopupWindow.isShowing()? R.mipmap.icon_expand_e : R.mipmap.icon_expand);
        rvAll.setLayoutManager(new LinearLayoutManager(this));
        allPaperAdapter = new AllPaperAdapter(samplePaperBeans);
        rvAll.setAdapter(allPaperAdapter);
        mEditText.setOnEditorActionListener(new EditEditorActionListener());
        mEditText.addTextChangedListener(new EditTextChangeListener());
    }
    private void initPopWindow() {
        mPopView = getLayoutInflater().inflate(R.layout.view_expand, null);
        // 将转换的View放置到 新建一个popuwindow对象中
        mPopupWindow = new PopupWindow(mPopView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        // 点击popuwindow外让其消失
        mPopupWindow.setOutsideTouchable(true);
        //获取焦点
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ivExpand.setImageResource( R.mipmap.icon_expand);
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_expand:
                showPopWindow();
                break;
        }
    }
    protected class EditEditorActionListener implements TextView.OnEditorActionListener {

        @Override
        public boolean onEditorAction(TextView textView, int actionId,
                                      KeyEvent keyEvent) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchPaperByKeyword();
                tvTitleName.setText("搜索结果");
            }
            return true;
        }
    }
    private void searchPaperByKeyword() {
        mSearchList = new ArrayList<>();
        String trim = mEditText.getText().toString().trim();
        if (System.currentTimeMillis() - mLastSearchTime > 1000) {
            mLastSearchTime = System.currentTimeMillis();
        } else {
            return;
        }
        if (!TextUtils.isEmpty(trim)) {
            searchPaperData(trim);
        }
        hideSoftKeyboard(this);
    }
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    /* public void hideKeyboard() {
         if (mInputManager == null) {
             mInputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
         }
         if (this.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams
                 .SOFT_INPUT_STATE_HIDDEN) {
             Log.i("tj","2");
             if (getCurrentFocus() != null) {
                 Log.i("tj","3");
                 mInputManager.hideSoftInputFromWindow(this.getCurrentFocus()
                         .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
             }
         }
     }*/
    private void searchPaperData(String keyString) {
        mSearchList.clear();
        allPaperAdapter.setKeyString(keyString);
        for (int i = 0; i < samplePaperBeans.size(); i++) {
            if (null != samplePaperBeans.get(i).getPaperName() && samplePaperBeans.get(i)
                    .getPaperName().toLowerCase().contains(keyString.toLowerCase())) {
                mSearchList.add(samplePaperBeans.get(i));
            }
        }
        //dismissProcessDialog();
        if (mSearchList.size() > 0) {
            //mNodataLayout.setVisibility(View.GONE);
            rvAll.setVisibility(View.VISIBLE);
            noDate.setVisibility(View.GONE);
            allPaperAdapter.updateData(mSearchList);
        } else {
            rvAll.setVisibility(View.GONE);
            noDate.setVisibility(View.VISIBLE);
        }
    }

    private class EditTextChangeListener implements TextWatcher {
        @Override
        public void afterTextChanged(Editable s) {
            String s1 = s + "";
            if (s1.length() > 0) {

            } else {
                rvAll.setVisibility(View.VISIBLE);
                noDate.setVisibility(View.GONE);
                allPaperAdapter.updateData(samplePaperBeans);
                tvTitleName.setText(titleName);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {

            if (TextUtils.isEmpty(arg0.toString())) {

            } else {

            }
        }
    }
    private void showPopWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
            mPopupWindow.showAsDropDown(ivExpand, 0, 0);
            ivExpand.setImageResource( R.mipmap.icon_expand_e);
        }
    }
}

